package com.cykj.service.impl;

import com.cykj.dto.ResponseDTO;
import com.cykj.entity.OrdersDO;
import com.cykj.mapper.OrderMapper;
import com.cykj.mqEvent.CancelOrderEvent;
import com.cykj.service.IOrderService;
import com.cykj.vo.CyOrderVO;
import com.cykj.vo.OrdersVO;
import com.google.protobuf.Message;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Project:JDMS
 * Package:com.cykj.service.impl
 *
 * @Description:
 * @Author:其一
 * @CreateTime: 2025-07-24-12-44
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public ResponseDTO selectAllById(OrdersVO ordersVO) {
        List<OrdersDO> list =orderMapper.selectAllById(ordersVO);
        return ResponseDTO.success("查询成功",list);
    }

    @Override
    public ResponseDTO buy(Integer userId, Integer goodId, int count) {
        if (!redisTemplate.hasKey("goodStock:"+goodId)) {
            return ResponseDTO.error(0,"商品不存在");
        }
        if(Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get("goodStock:"+goodId)))<count){
            return ResponseDTO.error(-1,"库存不足");
        }

        redisTemplate.opsForValue().decrement("goodStock:"+goodId,count);
        CyOrderVO cyOrderVO = new CyOrderVO();
        cyOrderVO.setBuyCount(count);
        cyOrderVO.setGoodId(goodId);
        cyOrderVO.setUserId(userId);
        Integer i = orderMapper.insertOrder(cyOrderVO);
        if(i==null || i==0){
            return ResponseDTO.error("购买失败");
        }
        //发送延时消息
        System.out.println(cyOrderVO.getId());
        CancelOrderEvent cancelOrderEvent = new CancelOrderEvent(cyOrderVO.getId());
        GenericMessage<CancelOrderEvent> cancelOrderEventGenericMessage = new GenericMessage<>(cancelOrderEvent);
        rocketMQTemplate.asyncSend("cancel-order", cancelOrderEventGenericMessage, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("消息发送成功");
            }
            @Override
            public void onException(Throwable throwable) {
                System.out.println("消息发送失败");
                redisTemplate.opsForValue().increment("goodStock:"+goodId,count);
            }
        },3000,3);
        return ResponseDTO.success("购买成功");
    }
}
